import gc
import random
import threading
import time,datetime,sys
from selenium import webdriver
import unittest
from pywinauto.application import Application
from psutil import process_iter
from pywinauto import mouse
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
import traceback

import tools
from tools import *

class ParametrizedTestCase(unittest.TestCase):
    """ TestCase classes that want to be parametrized should
        inherit from this class.
    """

    def __init__(self, methodName='runTest', param=None):
        super(ParametrizedTestCase, self).__init__(methodName)
        self.param = param

    @staticmethod
    def parametrize(testcase_class, param=None):
        """ Create a suite containing all tests taken from the given
            subclass, passing them the parameter 'param'.
        """
        testloader = unittest.TestLoader()
        testnames = testloader.getTestCaseNames(testcase_class)
        suite = unittest.TestSuite()
        for name in testnames:
            suite.addTest(testcase_class(name, param=param))
        return suite

class Global_Lock:
    sent_pic_lock = threading.Lock()

class add_promote_goods(ParametrizedTestCase):

    def run_start(self, driver, channelShopId):

        self.login_wechat_shop(driver, channelShopId)
        if self.to_optimal_alliance(driver, channelShopId):
            self.to_promote_manager(driver, channelShopId)
        else:
            while not self.to_optimal_alliance(driver, channelShopId):
                time.sleep(30)
                send_person_msg('17326075282', channelShopId, '###对比视频号小店ID失败###', '请检查视频号小店扫码使用了正确的微信')
        # 开始执行
        while 1:
            try:
                # 每隔10分钟判断是否登出了
                currentMinute = int(datetime.datetime.now().strftime('%M'))
                if currentMinute % random.randint(2,10) == 0:
                    self.check_login_status(driver, channelShopId)
                # if currentMinute % 10 == 0:
                #     while not self.to_optimal_alliance(driver, channelShopId):
                #         self.relogin(driver, channelShopId)
                gc.collect()
                self.add_promote_flow(driver, channelShopId)
            except Exception as e:
                print("driver is:%s" % driver)
                gc.collect()
                send_group_msg(channelShopId, "run_start步骤异常", e)
                self.run_start(driver, channelShopId)

    # 首页->进入优选联盟->推广管理
    def to_promote_manager(self, driver, channelShopId):
        # 判断是否打开优选联盟二级目录
        print("to_promote_manager")
        try:
            if not is_element_exist_css(driver, "#menuBar > li:nth-child(10) > span.weui-desktop-menu__link.arrow-up"):
                driver.find_element(By.CSS_SELECTOR, "#menuBar > li:nth-child(1) > a > span > span").click()
                time.sleep(2)
                if is_element_exist_css(driver, "#menuBar > li:nth-child(10) > span.weui-desktop-menu__link.arrow-up"):
                    driver.find_element(By.CSS_SELECTOR, "li:nth-of-type(10) > .weui-desktop-sub-menu.weui-desktop-sub-menu__current > li:nth-of-type(1) > .weui-desktop-menu__link  .weui-desktop-menu__name").click()
                else:
                    driver.find_element(By.CSS_SELECTOR, "#menuBar > li:nth-child(10) > span").click()
                    driver.find_element(By.CSS_SELECTOR, "li:nth-of-type(10) > .weui-desktop-sub-menu.weui-desktop-sub-menu__current > li:nth-of-type(1) > .weui-desktop-menu__link  .weui-desktop-menu__name").click()
                time.sleep(3)
            else:
                driver.find_element(By.CSS_SELECTOR,"li:nth-of-type(10) > .weui-desktop-sub-menu.weui-desktop-sub-menu__current > li:nth-of-type(1) > .weui-desktop-menu__link  .weui-desktop-menu__name").click()
        except Exception as e:
            send_error_msg(channelShopId, "进入优选联盟->推广管理", e)

    # 推广管理-> 专属推广
    def to_spec_promote_page(self, driver, channelShopId):
        # 进入专属推广
        print("to_spec_promote_page")
        try:
            time.sleep(2)
            # 切换到shadow-root
            shadow_driver = driver.execute_script(
            "return document.querySelector('#js_container_box > div.col_main > div.col_main_inner > div > div > micro-app').shadowRoot.children[1]")
            shadow_driver.find_element(By.CSS_SELECTOR,"#app > div.weui-desktop-block > div > div > div.weui-desktop-tab.weui-desktop-tab_title > div > ul > li:nth-child(3) > a").click()
            time.sleep(2)
            return shadow_driver
        except Exception as e:
            send_error_msg(channelShopId, "推广管理->专属推广", e)

    # 添加专属推广商品
    def add_spec_promote(self, shadow_driver, sx_ret_spec, channelShopId):
        # 添加专属推广
        print("add_spec_promote")
        try:
            # 点击添加
            time.sleep(2)
            shadow_driver.find_element(By.CSS_SELECTOR,"#app > div.weui-desktop-block > div > div > div:nth-child(2) > div:nth-child(2) > div > button").click()
            time.sleep(2)
            # 点击搜索
            shadow_driver.find_element(By.CSS_SELECTOR, "#app > div.weui-desktop-block > div > div > div:nth-child(2) > div:nth-child(2) > div.special-p-dialog-container > div > div.weui-desktop-dialog__wrp.specialPContainer.half-dialog > div > div.weui-desktop-dialog__bd > div > div:nth-child(2) > div > div.search-box > div > div.weui-desktop-form__input-area > span > input").send_keys(sx_ret_spec["productId"])
            shadow_driver.find_element(By.CSS_SELECTOR,"#app > div.weui-desktop-block > div > div > div:nth-child(2) > div:nth-child(2) > div.special-p-dialog-container > div > div.weui-desktop-dialog__wrp.specialPContainer.half-dialog > div > div.weui-desktop-dialog__bd > div > div:nth-child(2) > div > div.search-box > div > div.weui-desktop-form__input-area > span > span > button").click()
            time.sleep(5)
            # 是否搜索到
            if is_element_exist_css(shadow_driver,"div.weui-desktop-table__loading-content__slot > div > div > div.weui-desktop-table__main__body > table > tbody > tr > td.weui-desktop-table__tr-border.goods_info.firstColAfterCheckbox > div > div > div"):
                # 选中
                shadow_driver.find_element(By.CSS_SELECTOR,"div.weui-desktop-table__loading-content__slot > div > div > div.weui-desktop-table__main__header > table > thead > tr > th:nth-child(1) > label > i").click()
                # 点击下一步
                shadow_driver.find_element(By.CSS_SELECTOR,"div.weui-desktop-dialog__wrp.specialPContainer.half-dialog > div > div.weui-desktop-dialog__ft > div > div.flex > div:nth-child(2) > button").click()
                time.sleep(2)
                # 是否能进入下一步
                if is_element_exist_css(shadow_driver, "div.weui-desktop-dialog__wrp.specialPContainer.half-dialog > div > div.weui-desktop-dialog__ft > div > div.flex > div:nth-child(3) > button"):
                    # 输入视频号id
                    shadow_driver.find_element(By.CSS_SELECTOR,"div.search-c > div.search-box > div > div.weui-desktop-form__input-area > span > input").send_keys(sx_ret_spec["videoNumberId"])
                    time.sleep(1)
                    # 点击搜索视频号id
                    shadow_driver.find_element(By.CSS_SELECTOR,"div.search-c > div.search-box > div > div.weui-desktop-form__input-area > span > span > button").click()
                    time.sleep(2)
                    # 判断是否搜索到达人
                    if is_element_exist_css(shadow_driver,"div.weui-desktop-dialog__bd > div > div.self-center > div > div.pman-c > div > div > div > div.checkbox-c"):
                        # 选中达人
                        shadow_driver.find_element(By.CSS_SELECTOR,"div.weui-desktop-dialog__bd > div > div.self-center > div > div.pman-c > div > div > div > div.checkbox-c").click()
                        # 筛选时间
                        time.sleep(1)
                        shadow_driver.find_element(By.CSS_SELECTOR,"div.self-center > div > div.time-c > div.time-box > dl > dt > span:nth-child(1) > div > span > input").click()
                        # 选中永久
                        shadow_driver.find_element(By.CSS_SELECTOR,"div.weui-desktop-picker__panel.weui-desktop-picker__panel_left-slot > div.weui-desktop-picker__panel__quick-select.weui-desktop-picker__panel__quick-select_time > div").click()
                        time.sleep(1)
                        # 点击确定
                        shadow_driver.find_element(By.CSS_SELECTOR,"div.weui-desktop-dialog__wrp.specialPContainer.half-dialog > div > div.weui-desktop-dialog__ft > div > div.flex > div:nth-child(3) > button").click()
                        time.sleep(2)
                        return True
                    else:
                        print("未找到达人")
                        # 发送状态不正确的回调
                        send_spec_goods_result(sx_ret_spec["videoNumberId"], sx_ret_spec["productId"],sx_ret_spec["channelShopId"], 3)
                        # 发送达人状态不对的请求
                        send_bind_account_result(channelShopId, sx_ret_spec["videoNumberId"], 3)
                        print("达人不在合作者的状态")
                        self.check_frame(shadow_driver)
                        return False
                elif is_element_exist_css(shadow_driver, "tbody > tr > td.weui-desktop-table__tr-border.goods_info.firstColAfterCheckbox > div > div > div > div.item-basic-spu.flex.items-center > div:nth-child(2)"):
                    if shadow_driver.find_element(By.CSS_SELECTOR, "tbody > tr > td.weui-desktop-table__tr-border.goods_info.firstColAfterCheckbox > div > div > div > div.item-basic-spu.flex.items-center > div:nth-child(2)").text == "未达标，暂不支持推广" \
                            or shadow_driver.find_element(By.CSS_SELECTOR, "tbody > tr > td.weui-desktop-table__tr-border.goods_info.firstColAfterCheckbox > div > div > div > div.item-basic-spu.flex.items-center > div:nth-child(2)").text == "该类目商品暂不允许发布到联盟":
                        send_spec_goods_result(sx_ret_spec["videoNumberId"], sx_ret_spec["productId"], sx_ret_spec["channelShopId"], 1001)
                        self.check_frame(shadow_driver)
                        return False
            else:
                print("未找到专属推广商品")
                # 发送状态不正确的回调
                send_spec_goods_result(sx_ret_spec["videoNumberId"], sx_ret_spec["productId"],sx_ret_spec["channelShopId"], 0)
                return False
        except Exception as e:
            send_error_msg(channelShopId, "推广管理->专属推广", e)

    def check_frame(self, shadow_driver):
        # 是否还在添加流程
        if is_element_exist_css(shadow_driver, "div.weui-desktop-dialog__wrp.specialPContainer.half-dialog > div > div.weui-desktop-dialog__hd > button"):
            shadow_driver.find_element(By.CSS_SELECTOR, "div.weui-desktop-dialog__wrp.specialPContainer.half-dialog > div > div.weui-desktop-dialog__hd > button").click()

    def check_normal_frame(self, shadow_driver):
        # 是否还在添加流程
        if is_element_exist_css(shadow_driver,
                                "div.v-transfer-dom > div.weui-desktop-dialog__wrp.normalPContainer.half-dialog > div > div.weui-desktop-dialog__hd > button"):
            shadow_driver.find_element(By.CSS_SELECTOR,
                                       "div.v-transfer-dom > div.weui-desktop-dialog__wrp.normalPContainer.half-dialog > div > div.weui-desktop-dialog__hd > button").click()
    # check 添加专属商品结果
    def check_add_spec_result(self, shadow_driver, sx_ret_spec, channelShopId):
        # 输入商品id
        try:
            shadow_driver.find_element(By.CSS_SELECTOR, "div.flex.items-center > div:nth-child(1) > div.weui-desktop-form__input-area > span > input").send_keys(sx_ret_spec["productId"])
            # 输入视频号id
            shadow_driver.find_element(By.CSS_SELECTOR, "div.flex.items-center > div:nth-child(2) > div.weui-desktop-form__input-area > span > input").send_keys(sx_ret_spec["videoNumberId"])
            # 点击搜索
            shadow_driver.find_element(By.CSS_SELECTOR, "div.weui-desktop-form__input-area > span > span > button").click()
            time.sleep(2)
            # 判断是否有【推广中】
            if is_element_exist_css(shadow_driver, "div.weui-desktop-table__loading-content__slot > div > div > table > tbody > tr > td:nth-child(4) > div > div"):
                if shadow_driver.find_element(By.CSS_SELECTOR, "div.weui-desktop-table__loading-content__slot > div > div > table > tbody > tr > td:nth-child(4) > div > div").text == '推广中':
                    send_spec_goods_result(sx_ret_spec["videoNumberId"], sx_ret_spec["productId"], sx_ret_spec["channelShopId"], 2)
                else:
                    send_spec_goods_result(sx_ret_spec["videoNumberId"], sx_ret_spec["productId"],sx_ret_spec["channelShopId"], 1)
            else:
                send_spec_goods_result(sx_ret_spec["videoNumberId"], sx_ret_spec["productId"], sx_ret_spec["channelShopId"], 1)
        except Exception as e:
            send_error_msg(channelShopId, "check_add_spec_result：", e)

    # 添加普通推广商品
    def add_normal_promote(self, shadow_driver, sx_ret_normal, channelShopId):
        # 进入普通推广
        print("add_normal_promote")
        try:
            time.sleep(2) #todo 增加判断frame
            self.check_normal_frame(shadow_driver)
            shadow_driver.find_element(By.CSS_SELECTOR, "#app > div.weui-desktop-block > div > div > div.weui-desktop-tab.weui-desktop-tab_title > div > ul > li:nth-child(1)").click()
            #搜索
            shadow_driver.find_element(By.CSS_SELECTOR, "#app > div.weui-desktop-block > div > div > div:nth-child(2) > div.flex.items-center > div > div.weui-desktop-form__input-area > span > input").click()
            shadow_driver.find_element(By.CSS_SELECTOR, "#app > div.weui-desktop-block > div > div > div:nth-child(2) > div.flex.items-center > div > div.weui-desktop-form__input-area > span > input").clear()
            shadow_driver.find_element(By.CSS_SELECTOR, "#app > div.weui-desktop-block > div > div > div:nth-child(2) > div.flex.items-center > div > div.weui-desktop-form__input-area > span > input").send_keys(sx_ret_normal["productId"])
            time.sleep(1)
            shadow_driver.find_element(By.CSS_SELECTOR,"div.weui-desktop-form__input-area > span > span > button").click()
            # 是否在推广中
            if is_element_exist_css(shadow_driver, "#app > div.weui-desktop-block > div > div > div.general-plan-table-container > div > div > div > div.weui-desktop-table__loading-content__slot > div > div > table > tbody > tr"):
                if shadow_driver.find_element(By.CSS_SELECTOR, "div.weui-desktop-table__loading-content__slot > div > div > table > tbody > tr > td:nth-child(5) > div > div").text == "推广中":
                    shadow_driver.find_element(By.CSS_SELECTOR, "div.weui-desktop-table__loading-content__slot > div > div > table > tbody > tr > td:nth-child(6) > div > div > div:nth-child(1) > span > a").click()
                    time.sleep(0.5)
                    shadow_driver.find_element(By.CSS_SELECTOR, "tbody > tr > td:nth-child(6) > div > div > div:nth-child(1) > div > div > div.weui-desktop-popover__desc > div > span > input").send_keys(sx_ret_normal["commissionRate"])
                    shadow_driver.find_element(By.CSS_SELECTOR, "div.weui-desktop-table__loading-content__slot > div > div > table > tbody > tr > td:nth-child(6) > div > div > div:nth-child(1) > div > div > div.weui-desktop-popover__bar > div > div:nth-child(2) > button").click()
                    # 再次点击搜索
                    time.sleep(3)
                    shadow_driver.find_element(By.CSS_SELECTOR,"div.weui-desktop-form__input-area > span > span > button").click()
                    # check 佣金更新后是否成功
                    self.check_normal_result_without_search(shadow_driver, sx_ret_normal, channelShopId)
            else:
                # 点击立即新增
                shadow_driver.find_element(By.CSS_SELECTOR, "#app > div.weui-desktop-block > div > div > div:nth-child(2) > div:nth-child(2) > div:nth-child(2) > button").click()
                time.sleep(2)
                # 输入商品id
                shadow_driver.find_element(By.CSS_SELECTOR, "div.search-box > div > div.weui-desktop-form__input-area > span > input").send_keys(sx_ret_normal["productId"])
                # 点击搜索
                shadow_driver.find_element(By.CSS_SELECTOR, "div.search-box > div > div.weui-desktop-form__input-area > span > span").click()
                time.sleep(2)
                # 是否可以搜到商品
                if is_element_exist_css(shadow_driver, "tbody > tr > td.weui-desktop-table__tr-border.goods_info.firstColAfterCheckbox > div"):
                    # 选中商品
                    shadow_driver.find_element(By.CSS_SELECTOR, "div.weui-desktop-table__loading-content__slot > div > div > div.weui-desktop-table__main__header > table > thead > tr > th:nth-child(1) > label > i").click()
                    if is_element_exist_css(shadow_driver, "div.set-batch-commission-container > div.set-batch-commission-input-box > div > span > input"):
                        # 编辑佣金率
                        time.sleep(1)
                        shadow_driver.find_element(By.CSS_SELECTOR,"td.weui-desktop-table__tr-border.goods_commission > div > div > div.set-commission-inputbox > div > span > input").click()
                        shadow_driver.find_element(By.CSS_SELECTOR,"td.weui-desktop-table__tr-border.goods_commission > div > div > div.set-commission-inputbox > div > span > input").send_keys(
                            Keys.BACK_SPACE)
                        shadow_driver.find_element(By.CSS_SELECTOR,"td.weui-desktop-table__tr-border.goods_commission > div > div > div.set-commission-inputbox > div > span > input").send_keys(sx_ret_normal["commissionRate"])
                        shadow_driver.find_element(By.CSS_SELECTOR, "div.weui-desktop-dialog__wrp.normalPContainer.half-dialog > div > div.weui-desktop-dialog__ft > div > div:nth-child(2) > button").click()
                        time.sleep(2)
                        # check 佣金更新后是否成功
                        self.check_normal_result(shadow_driver, sx_ret_normal, channelShopId)
                        send_normal_goods_result(sx_ret_normal['commissionRate'], sx_ret_normal['productId'], sx_ret_normal['channelShopId'], 2)
                        # 是否还在添加流程
                        self.check_normal_frame(shadow_driver)
                    elif is_element_exist_css(shadow_driver, "tbody > tr > td.weui-desktop-table__tr-border.goods_info.firstColAfterCheckbox > div > div > div > div.item-basic-spu.flex.items-center > div"):
                        send_normal_goods_result(sx_ret_normal["commissionRate"], sx_ret_normal["productId"],sx_ret_normal["channelShopId"], 1001)
                        self.check_normal_frame(shadow_driver)
                        # if shadow_driver.find_element(By.CSS_SELECTOR, "tbody > tr > td.weui-desktop-table__tr-border.goods_info.firstColAfterCheckbox > div > div > div > div.item-basic-spu.flex.items-center > div:nth-child(2)").text == "未达标，暂不支持推广":
                    else:
                        send_normal_goods_result(sx_ret_normal['commissionRate'], sx_ret_normal['productId'],sx_ret_normal['channelShopId'], 0)
                        self.check_normal_frame(shadow_driver)
                else:
                    send_normal_goods_result(sx_ret_normal['commissionRate'], sx_ret_normal['productId'], sx_ret_normal['channelShopId'], 0)
                    self.check_normal_frame(shadow_driver)
        except Exception as e:
            send_error_msg(channelShopId, "add_normal_promote：", e)

    def check_normal_result(self, shadow_driver, sx_ret_normal, channelShopId):
        # check 普通商品添加结果
        print("check_normal_result")
        try:
            # 输入框直接输入并搜索
            shadow_driver.find_element(By.CSS_SELECTOR, "#app > div.weui-desktop-block > div > div > div:nth-child(2) > div.flex.items-center > div > div.weui-desktop-form__input-area > span > input").click()
            shadow_driver.find_element(By.CSS_SELECTOR, "#app > div.weui-desktop-block > div > div > div:nth-child(2) > div.flex.items-center > div > div.weui-desktop-form__input-area > span > input").clear()
            shadow_driver.find_element(By.CSS_SELECTOR,"#app > div.weui-desktop-block > div > div > div:nth-child(2) > div.flex.items-center > div > div.weui-desktop-form__input-area > span > input").send_keys(sx_ret_normal["productId"])
            shadow_driver.find_element(By.CSS_SELECTOR,"div.weui-desktop-form__input-area > span > span > button").click()
            if shadow_driver.find_element(By.CSS_SELECTOR, "div.weui-desktop-table__loading-content__slot > div > div > table > tbody > tr > td:nth-child(4) > div > div").text[:-1] == sx_ret_normal['commissionRate']\
                    and shadow_driver.find_element(By.CSS_SELECTOR, "div.weui-desktop-table__loading-content__slot > div > div > table > tbody > tr > td:nth-child(5) > div > div").text == "推广中":
                    send_normal_goods_result(sx_ret_normal['commissionRate'], sx_ret_normal['productId'], sx_ret_normal['channelShopId'], 2)
            elif shadow_driver.find_element(By.CSS_SELECTOR, "div.weui-desktop-table__loading-content__slot > div > div > table > tbody > tr > td:nth-child(5) > div > div").text == "已下架":
                send_normal_goods_result(sx_ret_normal['commissionRate'], sx_ret_normal['productId'], sx_ret_normal['channelShopId'], 4)
                send_group_msg(channelShopId, "check_normal_result推广更新普通商品失败", "商品信息：%s" % sx_ret_normal)
        except Exception as e:
            send_error_msg(channelShopId, "check_normal_result：", e)

    def check_normal_result_without_search(self, shadow_driver, sx_ret_normal, channelShopId):
        # check 普通商品编辑结果check
        print("check_normal_result_without_search")
        time.sleep(2)
        try:
            if shadow_driver.find_element(By.CSS_SELECTOR, "div.weui-desktop-table__loading-content__slot > div > div > table > tbody > tr > td:nth-child(4) > div > div").text[:-1] == str(sx_ret_normal['commissionRate'])\
                    and shadow_driver.find_element(By.CSS_SELECTOR, "div.weui-desktop-table__loading-content__slot > div > div > table > tbody > tr > td:nth-child(5) > div > div").text == "推广中":
                    send_normal_goods_result(sx_ret_normal['commissionRate'], sx_ret_normal['productId'], sx_ret_normal['channelShopId'], 2)
            elif shadow_driver.find_element(By.CSS_SELECTOR, "div.weui-desktop-table__loading-content__slot > div > div > table > tbody > tr > td:nth-child(5) > div > div").text == "已下架":
                send_normal_goods_result(sx_ret_normal['commissionRate'], sx_ret_normal['productId'], sx_ret_normal['channelShopId'], 4)
                send_group_msg(channelShopId, "check_normal_result_without_search推广更新普通商品失败,商品已下架", "商品信息：%s" % sx_ret_normal)
            else:
                send_group_msg(channelShopId, "check_normal_result_without_search推广更新普通商品失败", "商品信息：%s" % sx_ret_normal)
            # shadow_driver.find_element(By.CSS_SELECTOR, "#app > div.weui-desktop-block > div > div > div:nth-child(2) > div.flex.items-center > div > div.weui-desktop-form__input-area > span > input").click()
            shadow_driver.find_element(By.CSS_SELECTOR, "#app > div.weui-desktop-block > div > div > div:nth-child(2) > div.flex.items-center > div > div.weui-desktop-form__input-area > span > input").clear()
        except Exception as e:
            send_error_msg(channelShopId, "check_normal_result_without_search：", e)


    # 推广管理-> 普通推广
    def to_normal_promote_page(self, driver, channelShopId):
        # 进入普通推广
        print("to_normal_promote_page")
        try:
            time.sleep(2)
            # 切换到shadow-root
            shadow_driver = driver.execute_script(
                "return document.querySelector('#js_container_box > div.col_main > div.col_main_inner > div > div > micro-app').shadowRoot.children[1]")
            time.sleep(1)
            shadow_driver.find_element(By.CSS_SELECTOR,"#app > div.weui-desktop-block > div > div > div.weui-desktop-tab.weui-desktop-tab_title > div > ul > li:nth-child(1) > a").click()
            time.sleep(2)
            return shadow_driver
        except Exception as e:
            send_error_msg(channelShopId, "推广管理->普通推广", e)

    # 判断是否有需要推广的商品
    def getPromoteTask(self, url, channelShopId):

        try:
            ret = RequestsEdit.get(url)
            # result_list = []
            if ret != None:
                ret_json = ret.json()['data']
                # len_list = len(ret_json)
                # for i in range(0, len_list, 1):
                #     if ret_json[i]['channelShopId'] == channelShopId:
                #         result_list.append(ret_json[i])
                # return result_list
                return ret_json
            else:
                return None
        except Exception as e:
            send_group_msg("getPromoteTask", "getPromoteTask异常", e)


    def add_promote_flow(self, driver, channelShopId):
        print("start add_promote_flow")
        try:
            special_promote_url = "https://msd.guang.com/client/channels/rpa/query-promotable-special-goods?channelShopId=%s"%channelShopId
            normal_promote_url = "https://msd.guang.com/client/channels/rpa/query-promotable-common-goods?channelShopId=%s"%channelShopId
            sx_ret_spec = self.getPromoteTask(special_promote_url, channelShopId)
            if sx_ret_spec != None:
                self.to_promote_manager(driver, channelShopId)
                shadow_driver = driver.execute_script("return document.querySelector('#js_container_box > div.col_main > div.col_main_inner > div > div > micro-app').shadowRoot.children[1]")
                shadow_driver.find_element(By.CSS_SELECTOR, "#app > div.weui-desktop-block > div > div > div.weui-desktop-tab.weui-desktop-tab_title > div > ul > li:nth-child(3) > a").click()
                add_flag = self.add_spec_promote(shadow_driver, sx_ret_spec, channelShopId)
                self.check_frame(shadow_driver)
                # check 结果
                if add_flag:
                    self.check_add_spec_result(shadow_driver, sx_ret_spec, channelShopId)
            else:
                sx_ret_normal = self.getPromoteTask(normal_promote_url, channelShopId)
                if sx_ret_normal != None:
                    self.to_promote_manager(driver, channelShopId)
                    shadow_driver = driver.execute_script("return document.querySelector('#js_container_box > div.col_main > div.col_main_inner > div > div > micro-app').shadowRoot.children[1]")
                    self.add_normal_promote(shadow_driver, sx_ret_normal, channelShopId)
                    driver.refresh()
        except Exception as e:
            send_error_msg(channelShopId, "add_business_flow: ", e)
            driver.refresh()



    def login_wechat_shop(self, driver, channelShopId):
        # 登录视频号小店
        try:
            print("开始登录视频号小店")
            driver.refresh()
            driver.get("https://channels.weixin.qq.com/shop")
            time.sleep(5)
            driver.maximize_window()
            driver.implicitly_wait(5)
            print("爱逛管理员请扫码")
            # 判断是否需要扫码登录
            if is_element_exist_css(driver, ".login__type__container__scan__qrcode"):
                wechat_shop_QR_code = driver.find_element(By.CSS_SELECTOR ,".login__type__container__scan__qrcode")
                wechat_shop_QR_code_path = scan_pic_path + 'login_wechat_shop_QR_code' + time.strftime(
                    "%Y-%m-%d-%H_%M_%S", time.localtime(time.time())) + ".png"
                wechat_shop_QR_code.screenshot(wechat_shop_QR_code_path)
                # 发送二维码给对应微信，微信昵称备注为视频号小店id
                time.sleep(2)
                self.sent_pic(channelShopId, wechat_shop_QR_code_path)
                time.sleep(2)
            # 判断是否扫码成功
            pointer = 1
            while 1 == 1:
                if is_element_exist_css(driver, ".can-hover"):
                    break
                else:
                    print("正在等待爱逛管理员请扫码")
                    time.sleep(2)
                    pointer += 1
                    if pointer == 150:
                        self.login_wechat_shop(driver,channelShopId)
            print("登录成功")
        except Exception as e:
            send_group_msg("登录", "login_wechat_shop登录视频号小店", e)
            self.login_wechat_shop(driver, channelShopId)

    def check_login_status(self,driver,channelShopId):
        # check登录状态
        print("开始check_login_status")
        try:
            driver.refresh()
            time.sleep(5)
            if is_element_exist_css(driver, ".can-hover"):
                print("已经是登录状态")
            else:
                print("登录态失效，爱逛管理员请扫码")
                if is_element_exist_css(driver, "#body > div > div > div > div > h2 > a"):
                    driver.find_element(By.CSS_SELECTOR, "#body > div > div > div > div > h2 > a").click()
                    time.sleep(random.randint(20,40))
                    wechat_shop_QR_code = driver.find_element(By.CSS_SELECTOR ,".login__type__container__scan__qrcode")
                    wechat_shop_QR_code_path = scan_pic_path + 'login_wechat_shop_QR_code' + time.strftime(
                        "%Y-%m-%d-%H_%M_%S", time.localtime(time.time())) + ".png"
                    wechat_shop_QR_code.screenshot(wechat_shop_QR_code_path)
                    # 发送二维码给对应微信，微信昵称备注为视频号小店id
                    time.sleep(2)
                    self.sent_pic(channelShopId, wechat_shop_QR_code_path)
                    # 判断是否扫码成功
                    pointer = 1
                    while 1 == 1:
                        if is_element_exist_css(driver, ".can-hover"):
                            break
                        else:
                            print("等待爱逛管理员请扫码")
                            time.sleep(2)
                            pointer += 1
                            if pointer == 150:
                                self.login_wechat_shop(driver,channelShopId)
                    print("扫码登录成功")
                else:
                    driver.refresh()
        except Exception as e:
            send_group_msg("登录", "login_wechat_shop登录视频号小店", e)
            self.login_wechat_shop(driver, channelShopId)

    # 进入优选联盟->店铺管理->基础信息 判断小店信息是否正确
    def to_optimal_alliance(self, driver, channelShopId):
        # return True
        try:
            # 判断是否打开店铺管理二级目录
            print("to_optimal_alliance-》进入优选联盟->店铺管理->基础信息 判断小店信息是否正确")
            if is_element_exist_css(driver,
                                    "#menuBar .weui-desktop-menu_:nth-of-type(2) > .weui-desktop-menu__link:nth-of-type(1)"):
                driver.find_element(By.CSS_SELECTOR,
                                    "#menuBar .weui-desktop-menu_:nth-of-type(2) > .weui-desktop-menu__link:nth-of-type(1)").click()
            print("打开基础信息")
            # 打开基础信息
            driver.find_element(By.CSS_SELECTOR,
                                "li:nth-of-type(2) > .weui-desktop-sub-menu.weui-desktop-sub-menu__current > li:nth-of-type(1) > .weui-desktop-menu__link  .weui-desktop-menu__name").click()
            # 切换shadow_driver
            shadow_driver = self.switch_shadow(driver, channelShopId)
            # 获取小店id
            print("通过元素获取小店id")
            current_shop_id = shadow_driver.find_element(By.CSS_SELECTOR,
                                                         "#app > div > div:nth-child(3) > div:nth-child(1) > div > div.loading_content_slot > div:nth-child(2) > div > div.table_wrp > table > tbody > tr:nth-child(1) > td:nth-child(2) > div").text
            print("获取到当前视频号小店id为：%s" % current_shop_id)
            if channelShopId == current_shop_id:
                return True
            else:
                send_group_msg(channelShopId, "判断小店信息是否正确", "视频号小店ID对应不上")
                return False
        except Exception as e:
            send_group_msg(channelShopId, "判断小店基础信息", e)

    # 重新登录
    def relogin(self, driver, channelShopId):
        try:
            # 退出登录
            print("relogin > 重新登录")
            if is_element_exist_css(driver, "#header > div > div > div.header_box_msg > div.header_box_item.personInfo > div"):
                driver.find_element(By.CSS_SELECTOR, "#header > div > div > div.header_box_msg > div.header_box_item.personInfo > div").click()
                driver.find_element(By.CSS_SELECTOR, "#header > div > div > div.header_box_msg > div.header_box_item.personInfo > div > div > div.info-bounce_bottom > ul > li > i").click()
                time.sleep(1)
            print("爱逛管理员请扫码")
            # 判断是否需要扫码登录
            if is_element_exist_css(driver, ".login__type__container__scan__qrcode"):
                wechat_shop_QR_code = driver.find_element(By.CSS_SELECTOR, ".login__type__container__scan__qrcode")
                wechat_shop_QR_code_path = scan_pic_path + 'login_wechat_shop_QR_code' + time.strftime(
                    "%Y-%m-%d-%H_%M_%S", time.localtime(time.time())) + ".png"
                wechat_shop_QR_code.screenshot(wechat_shop_QR_code_path)
                # 发送二维码给对应微信，微信昵称备注为视频号小店id
                time.sleep(2)
                self.sent_pic(channelShopId, wechat_shop_QR_code_path)
                time.sleep(2)
            # 判断是否扫码成功
            pointer = 1
            while 1 == 1:
                if is_element_exist_css(driver, ".can-hover"):
                    break
                else:
                    print("正在等待爱逛管理员请扫码")
                    time.sleep(2)
                    pointer += 1
                    if pointer == 150:
                        self.login_wechat_shop(driver, channelShopId)
            print("登录成功")
        except Exception as e:
            send_group_msg(channelShopId, "判断小店基础信息", e)

    # 切换shadow-root
    def switch_shadow(self, driver, channelShopId):
        try:
            time.sleep(2)
            # 切换到shadow-root
            shadow_driver = driver.execute_script(
                "return document.querySelector('#js_container_box > div.col_main > div.col_main_inner > div:nth-child(2) > div > micro-app').shadowRoot.children[1]")

            time.sleep(2)
            return shadow_driver
        except Exception as e:
            send_error_msg(channelShopId, "切换shadow-root", e)


    def get_pid(self):
        PID = process_iter()
        for pid_temp in PID:
            pid_dic = pid_temp.as_dict(attrs=['pid', 'name'])
            if pid_dic['name'] == 'WeChat.exe':
                return pid_dic['pid']
        else:
            return 0
        print()

    # 左键点击某个控件
    def click_one(self, title='', control_type='', button='left', found_index=0, left=10, top=10, times=1):
        """
        :param title: 控件名称
        :param control_type: 控件类型
        :param button: left right middle 对应左、右、中三个键
        :param times: 点击次数
        :param found_index: 选择同名同类型多个控件中的第几个
        :param left: X 正方向修正
        :param top: Y 正方向修正
        :return:
        """
        # 在这里控件名称和类型，可以只选择一个，不过定位精准度不高
        if title == '' and control_type == '':
            raise ValueError('控件名和控件类型不可为空!')
        position = self.win.child_window(title=title, control_type=control_type, found_index=found_index).rectangle()
        for i in range(times):
            mouse.click(button=button, coords=(position.left + left, position.top + top))
            if times > 1:
                time.sleep(0.2)

    def connect_wechat(self):
        try:
            Application(backend='uia').start('C:\Program Files (x86)\Tencent\WeChat\WeChat.exe')
        except Exception as e:
            print()
        PID = self.get_pid()
        if PID == 0:
            print('未检测到微信运行')
            return 0
        else:
            self.app = Application(backend='uia')
            self.app.connect(process=PID)
            self.win = self.app[u'微信']
            print('已建立与微信链接')
        print()

    def sent_pic(self, channelShopId, path):
        name_dict = {'wx0829c079cc4ca92a': '爱逛旗舰店', 'wx035a17f37f622fdd': '爱逛女装专营店', 'wx865aea1241c3073b': '爱逛精选食品专营店', 'wx628fb890065d9bc3': '好生活商城', 'wx586a11c48a39cd71': '爱逛严选', 'wxeac71b9166004333': '爱逛臻选', 'wx3b1f2abf2088321f': '爱逛心选', 'wx9ab16ab3b9c65082': '爱逛优选'}        # lock = threading.Lock()
        Global_Lock.sent_pic_lock.acquire()
        self.connect_wechat()
        print("开始发送登录二维码给爱逛管理员")
        wx_name = name_dict.get(channelShopId)
        try:
            while 1 == 1:
                if self.win.child_window(title=wx_name, control_type='Text').exists(timeout=1):
                    print("点击管理员昵称")
                    time.sleep(3)
                    self.click_one(title=wx_name, control_type='Text')
                    time.sleep(1)
                    self.click_one(title="发送文件", control_type='Button')
                    print("点击发送文件")
                    time.sleep(1)
                    try:
                        self.win.child_window(title="文件名(N):", class_name='Edit').type_keys(path)
                        print("输入文件名")
                    except Exception as e:
                        print()
                    time.sleep(1)
                    try:
                        self.win.child_window(class_name='Button', title='打开(O)').click_input()
                        print("点击打开")
                    except Exception as e:
                        print()
                    time.sleep(1)
                    self.click_one(title="sendBtn", control_type='Button')
                    print("点击发送")
                    time.sleep(1)
                    break
                else:
                    print("当前界面未找到微信联系人：%s" %wx_name)
                    time.sleep(random.randint(30,60))
        except Exception as e:
            print(e)
            send_error_msg(channelShopId, "sent_pic", e)
        Global_Lock.sent_pic_lock.release()

    def test_run(self):
        self.g = globals()
        thread = []
        options = Options()
        options.add_argument("--incognito")
        driver_path = "C:\Python\Python38\Scripts\chromedriver.exe"
        driver_path1 = "C:\Python\Python38\Scripts\chromedriver1.exe"
        driver_path2 = "C:\Python\Python38\Scripts\chromedriver2.exe"
        driver_path3 = "C:\Python\Python38\Scripts\chromedriver3.exe"
        # driver_path4 = "C:\Python\Python38\Scripts\chromedriver4.exe"
        # driver_path5 = "C:\Python\Python38\Scripts\chromedriver5.exe"

        driver = webdriver.Chrome(driver_path, options=options)
        driver1 = webdriver.Chrome(driver_path1, options=options)
        driver2 = webdriver.Chrome(driver_path2, options=options)
        driver3 = webdriver.Chrome(driver_path3, options=options)
        # driver4 = webdriver.Chrome(driver_path4, options=options)
        # driver5 = webdriver.Chrome(driver_path5, options=options)
        driver.implicitly_wait(10)
        driver1.implicitly_wait(10)
        driver2.implicitly_wait(10)
        driver3.implicitly_wait(10)
        # driver4.implicitly_wait(10)
        # driver5.implicitly_wait(10)
        # 扫码登录必须按照对应关系，顺序：爱逛旗舰店，fushi,食
        # channelShopIdList = ["wx0829c079cc4ca92a", "wx035a17f37f622fdd", "wx865aea1241c3073b", 'wx628fb890065d9bc3', 'wx586a11c48a39cd71', 'wxeac71b9166004333']

        # channelShopIdList = ["wx865aea1241c3073b"]

        # driverList = [driver, driver1, driver2, driver3, driver4, driver5]
        driverList = [driver, driver1, driver2, driver3]

        # 开始执行
        for channelShopId in tools.channelShopIdList:
            driver = driverList[channelShopIdList.index(channelShopId)]
            # self.g['lock'] = threading.Lock()
            thread.append(threading.Thread(target=self.run_start, args=(driver, channelShopId)))

        for t in thread:
            time.sleep(20)
            t.start()

        for t in thread:
            t.join()

